from contextlib import closing
from genericpath import exists
from os import makedirs

import requests

headers = {
    "User-Agent": "Instagram 121.0.0.29.119 Android (10/3.4.0; 120; GT-I9220; HUAWEI;OXF-AN10; OXF-AN10; smdkc210; en_US)",
    "Cookie": "ig_did=C46FB9BE-AAB6-47CC-B182-CE4700653253; mid=X2rJUAABAAGDIvAOqlguQ88WCK7b; csrftoken=uLjszTbkzzUkyiBugutOCiYWcwv2i8pt; ds_user_id=12258097564; sessionid=12258097564%3A2H03iEui0e6Rzf%3A24; shbid=5175; shbts=1600833919.4517398; rur=FRC;"
}

dirName = "a.moodmoon"
userId = "2692009585"


def download(photo_url, dir_name, filename):
    if not exists(dir_name):
        makedirs(dir_name)
    print(filename + ": " + photo_url)
    jpg_filename = dir_name + '/' + filename
    if not exists(jpg_filename):
        with closing(requests.get(url=photo_url, headers=headers, stream=True, timeout=90)) as r:
            with open(jpg_filename, 'ab+') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
                        f.flush()
                f.close()


def toDownload(i):
    try:
        media_type = i.get('media_type')
        code = i.get('code')
        if media_type == 8:
            carousel_media = i.get('carousel_media')
            if carousel_media:
                for media in carousel_media:
                    toDownload(media)
        # elif media_type == 1:
        # elif media_type == 2:
        else:
            image_versions2 = i.get('image_versions2')
            if image_versions2:
                candidates = image_versions2.get('candidates')
                if candidates:
                    imgObj = candidates[0]
                    url = imgObj.get('url')
                    download(url, dirName, code + ".jpg")

        return True
    except:
        return False


def requestUrl(url, max_id):
    realUrl = url + max_id

    response = requests.get(realUrl, headers=headers).json()
    next_max_id = response.get('next_max_id')
    items = response.get('items')
    if items:
        for i in items:
            toDownload(i)
    if next_max_id and next_max_id != '':
        print("======= next_max_id : " + next_max_id + "=============")
        requestUrl(url, next_max_id)


if __name__ == '__main__':
    url = "https://i.instagram.com/api/v1/feed/user/" + userId + "/?count=12&max_id="
    requestUrl(url, '')
